/**
 * Copyright &copy; 2012-2014 <a href="https://github.cn.apestar">JeeSite</a> All rights reserved.
 */
package cn.apestar.modules.sys.web;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.ClientProtocolException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.apestar.common.DataContants;
import cn.apestar.common.config.Global;
import cn.apestar.common.exception.BaseException;
import cn.apestar.common.huanxin.huanXinUtil;
import cn.apestar.common.utils.CookieUtils;
import cn.apestar.common.utils.JedisUtils;
import cn.apestar.common.utils.StringUtils;
import cn.apestar.common.web.BaseController;
import cn.apestar.modules.sms.HttpUtil;
import cn.apestar.modules.sys.entity.User;
import cn.apestar.modules.sys.service.SystemService;
import cn.apestar.modules.sys.utils.UserUtils;
import redis.clients.jedis.Jedis;

/**
 * 用户Controller
 * @author ThinkGem
 * @version 2013-8-29
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/user/app")
public class UserAppController extends BaseController {

    @Autowired
    private SystemService systemService;

    @ModelAttribute
    public User get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return systemService.getUser(id);
        } else {
            return new User();
        }
    }

    /**
     * 返回用户信息
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "infoData")
    public User infoData() {
        return UserUtils.getUser();
    }

    /**
     * 1.注册帐号
     */
    @ResponseBody
    @RequestMapping(value = "registerUser")
    public Object registerUser(HttpServletRequest request, HttpServletResponse response, Model model) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repsw = request.getParameter("repsw");
        String companyName = request.getParameter("companyName");
        String serviceDistrict = request.getParameter("serviceDistrict");
        String serviceVillage = request.getParameter("serviceVillage");
        String isjjr = request.getParameter("isjjr");
        User user = new User();
        if (StringUtils.isEmpty(username)) {
            throw new BaseException("用户名不能为空！");
        }

        if (StringUtils.isEmpty(password)) {
            throw new BaseException("密码不能为空！");
        }

        if (!repsw.equals(password)) {
            throw new BaseException("2次输入的密码不匹配！");
        }
        User o = systemService.getUserByLoginName(username, null);
        if (o != null) {
            throw new BaseException("用户名已经存在！");
        }
        // 经纪人
        if ("true".equals(isjjr) || "1".equals(isjjr)) {
            user.setUserType(DataContants.USER_JJR);
            // user.setCompanyName(companyName);
        }
        // 用户
        else {
            user.setUserType(DataContants.USER_YH);
        }
        user.setPassword(SystemService.entryptPassword(password));
        user.setLoginName(username);
        user.setPhone(user.getLoginName());
        user.setName(user.getLoginName());
        user.setCreateDate(new Date());
        systemService.saveUser(user, false);
        huanXinUtil.regUser(user.getId(), username, username);
        return getDefaultSuccessMessage();
    }

    /**
     * 3.重置密码
     */
    @ResponseBody
    @RequestMapping(value = "/modifyPwd")
    public Object modifyPwd(HttpServletRequest request, HttpServletResponse response, Model model) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repsw = request.getParameter("repsw");
        User user = new User();
        if (StringUtils.isEmpty(username)) {
            throw new BaseException("用户名不能为空！");
        }

        if (StringUtils.isEmpty(password)) {
            throw new BaseException("密码不能为空！");
        }

        if (!repsw.equals(password)) {
            throw new BaseException("2次输入的密码不匹配！");
        }
        User o = systemService.getUserByLoginName(username, null);
        if (o == null) {
            throw new BaseException("用户名不存在！");
        }

        // o.setPassword(SystemService.entryptPassword(password));
        systemService.updatePasswordById(o.getId(), username, password);
        return getDefaultSuccessMessage();
    }

    /**
     * 4.修改个人用户密码
     * @param oldPassword
     * @param newPassword
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/mobile/modifyPwdOldPassword")
    public Object modifyPwd(String oldPassword, String newPassword) {
        User user = UserUtils.getUser();
        if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)) {
            if (SystemService.validatePassword(oldPassword, user.getPassword())) {
                systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
            } else {
                throw new BaseException("修改密码失败，旧密码错误！");
            }
        }
        return getDefaultSuccessMessage();
    }

    /**
     * 5.退出登录
     */
    @ResponseBody
    @RequestMapping(value = "out")
    public String logout(HttpServletRequest request, HttpServletResponse response, Model model) {
        CookieUtils.setCookie(response, "LOGINED", "false");
        if (UserUtils.getSubject() != null)
            UserUtils.getSubject().logout();
        Jedis jedis = null;
        try {
            jedis = JedisUtils.getResource();
            jedis.del(JedisUtils.getBytesKey("shiro_session_" + request.getSession().getId()));
        } catch (Exception e) {
            logger.error("update {} {}", request.getSession().getId(), request != null ? request.getRequestURI() : "", e);
        } finally {
            JedisUtils.returnResource(jedis);
        }
        return renderString(response, getSuccessMessage("退出成功", ""));
    }

    /**
     * 保存用户信息
     */
    @ResponseBody
    @RequestMapping(value = "/mobile/update")
    public Object updateUser(@ModelAttribute("User") User user, HttpServletRequest request, HttpServletResponse response, Model model) {
        systemService.saveUser(user, false);
        return getDefaultSuccessMessage();
    }

    /**
     * 根据ID取得用户信息
     */
    @ResponseBody
    @RequestMapping(value = "/getUserInformationById/{userId}")
    public Object getUserInformationById(HttpServletRequest request, HttpServletResponse response, Model model) {
        String userId = request.getParameter("userId");
        User u = new User();
        if (StringUtils.isEmpty(userId)) {
            return UserUtils.getUser();
        }
        u = UserUtils.get(userId);
        return getSuccessMessageObject(null, u);
    }

    @ResponseBody
    @RequestMapping(value = "clearCache/id/{userId}")
    public Object clearCache(@PathVariable("userId") String userId) throws ClientProtocolException, IOException {
        User user = UserUtils.get(userId);
        if (user != null) {
            String url = Global.getConfig("USER_CLEAR_URL");
            url = url.replace("{id}", user.getId());
            url = url.replace("{type}", user.getUserType());
            HttpUtil.ExecutionGET(url, null);
        }
        return getDefaultSuccessMessage();
    }

}
